import type { SavedConditionGroup } from '@/types/search'

// 高级搜索缓存管理
export class AdvancedSearchManager {

  private static getStorageKey(userId: string, pagePath: string): string {
    return `advanced-search-saved-conditions-${userId}-${pagePath}`
  }

  // 保存查询条件组到localStorage
  static saveSavedConditions(conditionGroups: SavedConditionGroup[], userId: string, pagePath: string): void {
    try {
      const key = this.getStorageKey(userId, pagePath)
      localStorage.setItem(key, JSON.stringify(conditionGroups))
    } catch (error) {
      console.error('保存高级搜索条件失败:', error)
    }
  }

  // 从localStorage加载查询条件组
  static loadSavedConditions(userId: string, pagePath: string): SavedConditionGroup[] {
    try {
      const key = this.getStorageKey(userId, pagePath)
      const stored = localStorage.getItem(key)
      if (stored) {
        return JSON.parse(stored)
      }
    } catch (error) {
      console.error('加载高级搜索条件失败:', error)
    }
    return []
  }

  // 清除查询条件组缓存
  static clearSavedConditions(userId: string, pagePath: string): void {
    try {
      const key = this.getStorageKey(userId, pagePath)
      localStorage.removeItem(key)
    } catch (error) {
      console.error('清除高级搜索条件失败:', error)
    }
  }

  // 添加新的查询条件组
  static addConditionGroup(group: Omit<SavedConditionGroup, 'id' | 'createdAt'>, userId: string, pagePath: string): void {
    const conditionGroups = this.loadSavedConditions(userId, pagePath)
    const newGroup: SavedConditionGroup = {
      ...group,
      id: Date.now().toString(),
      createdAt: new Date().toISOString()
    }
    conditionGroups.push(newGroup)
    this.saveSavedConditions(conditionGroups, userId, pagePath)
  }

  // 删除查询条件组
  static removeConditionGroup(id: string, userId: string, pagePath: string): void {
    const conditionGroups = this.loadSavedConditions(userId, pagePath)
    const filteredGroups = conditionGroups.filter(group => group.id !== id)
    this.saveSavedConditions(filteredGroups, userId, pagePath)
  }

  // 更新查询条件组
  static updateConditionGroup(id: string, updates: Partial<SavedConditionGroup>, userId: string, pagePath: string): void {
    const conditionGroups = this.loadSavedConditions(userId, pagePath)
    const index = conditionGroups.findIndex(group => group.id === id)
    if (index !== -1) {
      conditionGroups[index] = { ...conditionGroups[index], ...updates }
      this.saveSavedConditions(conditionGroups, userId, pagePath)
    }
  }
}